<template>
  <div>
    <!--   搜索-->
    <div style="display: flex;flex-wrap: wrap">
     <span style="margin:0 15px 10px 0">仓库： <el-select size="small" style="width: 200px;margin-right: 10px;" clearable
                                                       v-model="params.areaId"
                                                       filterable
                                                       placeholder="请选择仓库">
        <el-option v-for="item in provinceOptions" :key="item.area" :label="item.areaName"
                   :value="item.area">
        </el-option>
      </el-select></span>
      <span style="margin:0 15px 10px 0"> 编码：
        <el-input size="small" style="width: 200px"
                  clearable
                  v-model="params.skuCode"
                  placeholder="请输入编码"></el-input></span>
      <span style="margin:0 15px 10px 0"> 材料名称：
        <el-input size="small" style="width: 200px"
                  v-model="params.goodName"
                  clearable
                  placeholder="请输入材料名称"></el-input></span>
      <span style="margin:0 15px 10px 0"> 规格：
        <el-input size="small" style="width: 200px"
                  v-model="params.spec"
                  clearable
                  placeholder="请输入规格"></el-input></span>
      <span style="margin:0 15px 10px 0"> 位置坐标：
        <el-input size="small" style="width: 200px"
                  v-model="params.location"
                  clearable
                  placeholder="请输入位置坐标"></el-input></span>
      <span style="margin:0 15px 10px 0"> epc编码：
        <el-input size="small" style="width: 200px"
                  v-model="params.barcode"
                  clearable
                  placeholder="请输入编码"></el-input></span>
      <span style="margin:0 15px 10px 0">
        <el-button size="small" type="primary" @click="_search">查 询</el-button>
        <el-button size="small" type="primary" @click="_reset">重 置</el-button>
      </span>
    </div>

    <el-table :data="skuData" border
              height="calc(100vh - 280px)"
              :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
              :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
          fontSize: '12px'
        }">
      <el-table-column type="index" label='序号' width="80px"></el-table-column>
      <el-table-column prop="warehouse" label='仓库'></el-table-column>
      <el-table-column prop="skuCode" label='SKU编码' show-overflow-tooltip></el-table-column>
      <el-table-column prop="goodName" label='材料名称' show-overflow-tooltip></el-table-column>
      <el-table-column prop="unit" label='单位'></el-table-column>
      <el-table-column prop="color" label='颜色'></el-table-column>
      <el-table-column prop="size" label='规格' show-overflow-tooltip></el-table-column>
      <el-table-column prop="num" label='标签下单品库存' width="130px"></el-table-column>
      <el-table-column prop="maxGoodsNum" label='标签下单品最大库存' width="140px"></el-table-column>
      <el-table-column prop="position" label='位置坐标'></el-table-column>
      <el-table-column prop="updateTime" label='盘点更新时间' show-overflow-tooltip></el-table-column>
      <el-table-column prop="editTime" label='库存更新时间' show-overflow-tooltip></el-table-column>
      <el-table-column prop="epc" label='epc编码' width="150px" show-overflow-tooltip></el-table-column>
      <el-table-column label='操作' width="100px">
        <template v-slot:default="scope">
          <el-link style="color: #66b1ff;margin-right: 10px" @click='_edit(scope.row)' v-if="authority.includes(1202)">编辑</el-link>
          <el-link style="color: #66b1ff" @click='_down(scope.row)' v-if="authority.includes(1203)">下载</el-link>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        style="padding: 20px 0"
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[20, 30, 40, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
    >
    </el-pagination>
    <el-dialog :visible.sync="editDialog" title="编辑" width="35%">
      <div class="editDiv">
        <p><span style="width: 80px;">标签最大承载数量：</span>
          <el-input size="small" style="width: 250px" v-model="editForm.maxGoodsNum"></el-input>
        </p>
        <p><span style="width:80px;">位置坐标：</span>
          <el-input size="small" style="width: 250px" v-model="editForm.position"></el-input>
        </p>
      </div>
      <span slot="footer">
        <el-button size="small" @click="editDialog=false">取消</el-button>
        <el-button size="small" type="primary" @click="comfirmEdit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import quinn from "../../utils/quinn";

export default {
  name: "markList",
  data() {
    return {
      skuData: [],
      authority: [],
      editDialog: false,
      totalCount: 0,
      currentPage: 1,
      provinceOptions: [],
      editForm: {},
      params: {
        pageNumber: 1,
        pageSize: 20,
      }
    }
  },
  created() {
    const {authorityList = []} = quinn.getStorage('userData')
    this.authority = authorityList
    this.getList()
    this.getProvince()
  },
  methods: {
    getProvince() {
      this.$api.areaLedgerAreaList().then(res => {
        this.provinceOptions = res;
      })
    },
    getList() {
      this.$api.apiGetTagInfoList(this.params).then(res => {
        this.skuData = res.data
        this.totalCount = res.total
      })
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.params.pageNumber = val
      this.getList()
    },
    _search() {
      this.params.pageNumber = 1
      this.getList()
    },
    _reset() {
      this.params = this.$options.data.call(this).params
      this.getList()
    },
    _edit(row) {
      this.editDialog = true
      this.editForm = JSON.parse(JSON.stringify(row))
    },
    comfirmEdit() {
      const data = {
        maxGoodsNum: this.editForm.maxGoodsNum,
        position: this.editForm.position,
        id: this.editForm.id
      }
      console.log(data)
      this.$api.apiUpdateTagInfoNumAndLocation(data).then(res => {
        if (res == 1) {
          this.$message.success('编辑成功！')
          this.editDialog = false
          this.getList()
        }
      })
    },
    _down(row) {
      this.$message.success('正在下载中...')
      axios({
        url: `${this.$apiHost}/api/downLoadDocx`,
        method: 'post',
        headers: {
          token: window.$quinn.getStorage("token")
        },
        data: {
          shelfInfoList: [
            {label: "品牌", value: '零食很忙'},
            {label: "材料名称", value: row.goodName},
            {label: "颜色", value: row.color},
            {label: "规格", value: row.size},
            {label: "货架编号", value: row.position}
          ]
        }
      }).then(res => {
        //返回值为Base64字符串  需转为二进制流
        const base64Str = res.data.result;
        if (!base64Str) {
          this.$message.error('文件内容为空');
          return;
        }
        const byteCharacters = atob(base64Str);
        const byteNumbers = new Array(byteCharacters.length)
            .fill(0)
            .map((_, i) => byteCharacters.charCodeAt(i));
        const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray], {
          type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        });
        let fileName = `${row.goodName}.docx`; // 默认名
        const disposition = res.headers['content-disposition'];
        if (disposition) {
          const match = disposition.match(/filename="?([^"]+)"?/);
          if (match) {
            fileName = decodeURIComponent(match[1]);
            if (!fileName.includes('.')) fileName += '.docx';
          }
        }
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        URL.revokeObjectURL(link.href);
      }).catch(err => {
        console.error(err);
        this.$message.error('下载失败');
      });
    }

  }
}
</script>

<style scoped lang="less">
.editDiv {
  margin-left: 100px;

  p {
    margin-bottom: 10px;

    span {
      display: inline-block;
    }
  }
}
</style>